# 极简HTTP服务器 - Windows环境专用
# 不依赖任何外部库，使用Python标准库实现

import http.server
import socketserver
import json
import time
import sys
import os
import threading

# 设置工作目录为脚本所在目录
script_dir = os.path.dirname(os.path.abspath(__file__))
os.chdir(script_dir)

# 日志函数
def log(message):
    timestamp = time.strftime('%Y-%m-%d %H:%M:%S')
    print(f'[{timestamp}] {message}', flush=True)

# 简单的请求处理器
class SimpleHTTPRequestHandler(http.server.BaseHTTPRequestHandler):
    def do_GET(self):
        # 根路径返回欢迎信息
        if self.path == '/':
            self.send_response(200)
            self.send_header('Content-Type', 'text/html; charset=utf-8')
            self.end_headers()
            
            response = '''
            <!DOCTYPE html>
            <html>
            <head>
                <title>AI Chat System</title>
                <meta charset="utf-8">
                <style>
                    body { font-family: Arial, sans-serif; margin: 40px; text-align: center; }
                    h1 { color: #333; }
                    p { color: #666; }
                </style>
            </head>
            <body>
                <h1>AI聊天系统后端服务</h1>
                <p>服务运行中！API端点: <code>/api/ai/chat</code></p>
                <p>时间: ''' + time.strftime('%Y-%m-%d %H:%M:%S') + '''</p>
            </body>
            </html>
            '''
            
            self.wfile.write(response.encode('utf-8'))
            log(f'GET {self.path} 200')
        
        # 健康检查端点
        elif self.path == '/health':
            self.send_response(200)
            self.send_header('Content-Type', 'application/json')
            self.end_headers()
            
            response = json.dumps({
                'status': 'healthy',
                'timestamp': time.strftime('%Y-%m-%d %H:%M:%S')
            })
            
            self.wfile.write(response.encode('utf-8'))
            log(f'GET {self.path} 200')
        
        else:
            self.send_response(404)
            self.send_header('Content-Type', 'application/json')
            self.end_headers()
            
            response = json.dumps({
                'error': 'Not Found',
                'path': self.path
            })
            
            self.wfile.write(response.encode('utf-8'))
            log(f'GET {self.path} 404')
    
    def do_POST(self):
        # 模拟AI聊天API
        if self.path == '/api/ai/chat':
            # 读取请求体
            content_length = int(self.headers['Content-Length'])
            post_data = self.rfile.read(content_length)
            
            try:
                # 解析JSON数据
                data = json.loads(post_data)
                message = data.get('message', '')
                model_id = data.get('modelId', 'default')
                
                # 生成模拟回复
                responses = {
                    '你好': '你好！我是AI助手，很高兴为你服务。',
                    '你是谁': '我是一个AI聊天助手。',
                    '谢谢': '不客气！',
                    '再见': '再见！有需要随时找我。'
                }
                
                # 如果匹配到预设问题，使用预设回复，否则使用默认回复
                if message in responses:
                    reply = responses[message]
                else:
                    reply = f'我收到了你的消息："{message}"，这是来自{model_id}的回复。'
                
                # 返回成功响应
                self.send_response(200)
                self.send_header('Content-Type', 'application/json')
                self.end_headers()
                
                response = json.dumps({
                    'success': True,
                    'data': {
                        'reply': reply,
                        'modelId': model_id,
                        'timestamp': time.strftime('%Y-%m-%d %H:%M:%S')
                    }
                })
                
                self.wfile.write(response.encode('utf-8'))
                log(f'POST {self.path} 200 - 消息: {message}')
                
            except json.JSONDecodeError:
                self.send_response(400)
                self.send_header('Content-Type', 'application/json')
                self.end_headers()
                
                response = json.dumps({
                    'error': 'Invalid JSON'
                })
                
                self.wfile.write(response.encode('utf-8'))
                log(f'POST {self.path} 400 - Invalid JSON')
                
            except Exception as e:
                self.send_response(500)
                self.send_header('Content-Type', 'application/json')
                self.end_headers()
                
                response = json.dumps({
                    'error': str(e)
                })
                
                self.wfile.write(response.encode('utf-8'))
                log(f'POST {self.path} 500 - Error: {str(e)}')
        
        else:
            self.send_response(404)
            self.send_header('Content-Type', 'application/json')
            self.end_headers()
            
            response = json.dumps({
                'error': 'Not Found',
                'path': self.path
            })
            
            self.wfile.write(response.encode('utf-8'))
            log(f'POST {self.path} 404')
    
    # 禁用日志消息，使用我们自定义的日志
    def log_message(self, format, *args):
        return

# 主服务器类
class SimpleServer:
    def __init__(self, port=9999):
        self.port = port
        self.httpd = None
        self.server_thread = None
        self.running = False
    
    def start(self):
        """启动服务器"""
        try:
            # 创建服务器实例
            self.httpd = socketserver.TCPServer(('', self.port), SimpleHTTPRequestHandler)
            self.running = True
            
            log(f'服务器启动在 http://0.0.0.0:{self.port}')
            log(f'访问 http://localhost:{self.port} 查看欢迎页面')
            log(f'API端点: http://localhost:{self.port}/api/ai/chat')
            log(f'健康检查: http://localhost:{self.port}/health')
            
            # 在单独的线程中运行服务器
            self.server_thread = threading.Thread(target=self._run_server)
            self.server_thread.daemon = True
            self.server_thread.start()
            
            return True
            
        except Exception as e:
            log(f'启动服务器失败: {str(e)}')
            return False
    
    def _run_server(self):
        """服务器运行循环"""
        try:
            # 直接运行服务器，不再使用handle_request
            if self.httpd and self.running:
                self.httpd.serve_forever()
        except Exception as e:
            if self.running:  # 只有在运行中出现的错误才记录
                log(f'服务器运行错误: {str(e)}')
    
    def stop(self):
        """停止服务器"""
        log('停止服务器...')
        self.running = False
        
        # 关闭服务器
        if self.httpd:
            self.httpd.server_close()
        
        # 等待线程结束
        if self.server_thread:
            self.server_thread.join(timeout=2)
        
        log('服务器已停止')

# 主函数
def main():
    log('====== 极简HTTP服务器启动 ======')
    
    # 创建并启动服务器
    server = SimpleServer(port=8000)
    
    if not server.start():
        log('启动失败，3秒后退出...')
        time.sleep(3)
        return
    
    try:
        # 主循环保持运行
        log('服务器正在运行，按 Ctrl+C 停止...')
        while True:
            time.sleep(1)
    
    except KeyboardInterrupt:
        log('接收到停止信号')
    except Exception as e:
        log(f'发生异常: {str(e)}')
    finally:
        # 确保服务器停止
        server.stop()
        log('====== 服务器已退出 ======')

if __name__ == '__main__':
    main()